<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha256-xejo6yLi6vGtAjcMIsY8BHdKsLg7QynVlFMzdQgUuy8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"gz1234.gitee.io","root":"/","images":"/images","scheme":"Gemini","darkmode":true,"version":"8.12.3","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"flat"},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="认识 hooks Hook 是⼀一个特殊的函数，它可以让你“钩⼊入” React 的特性。例例如， useState 是允许你在 React 函数组件中添加 state 的 Hook  如果你在编写函数组件并意识到需要向其添加⼀一些 state，以前的做法是必须将其它转化为 class。现在你可以在现有的函数组件中使⽤用 Hook  函数组件强制刷新   const [,setCount] &#x3D; u">
<meta property="og:type" content="article">
<meta property="og:title" content="react-hooks">
<meta property="og:url" content="https://gz1234.gitee.io/2020/10/25/react%E7%AC%94%E8%AE%B0/react-hooks/index.html">
<meta property="og:site_name" content="郭泽">
<meta property="og:description" content="认识 hooks Hook 是⼀一个特殊的函数，它可以让你“钩⼊入” React 的特性。例例如， useState 是允许你在 React 函数组件中添加 state 的 Hook  如果你在编写函数组件并意识到需要向其添加⼀一些 state，以前的做法是必须将其它转化为 class。现在你可以在现有的函数组件中使⽤用 Hook  函数组件强制刷新   const [,setCount] &#x3D; u">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-10-25T02:08:09.000Z">
<meta property="article:modified_time" content="2023-03-22T11:56:23.517Z">
<meta property="article:author" content="郭泽">
<meta property="article:tag" content="react-hooks">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gz1234.gitee.io/2020/10/25/react%E7%AC%94%E8%AE%B0/react-hooks/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://gz1234.gitee.io/2020/10/25/react%E7%AC%94%E8%AE%B0/react-hooks/","path":"2020/10/25/react笔记/react-hooks/","title":"react-hooks"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>react-hooks | 郭泽</title>
  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">郭泽</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%AE%A4%E8%AF%86-hooks"><span class="nav-number">1.</span> <span class="nav-text">认识 hooks</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E2%BD%A4-Effect-Hook"><span class="nav-number">2.</span> <span class="nav-text">使⽤ Effect Hook</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#effect-%E7%9A%84%E6%9D%A1%E4%BB%B6%E6%89%A7%E2%BE%8F"><span class="nav-number">3.</span> <span class="nav-text">effect 的条件执⾏</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#effect-%E6%B8%85%E9%99%A4%E5%87%BD%E6%95%B0"><span class="nav-number">4.</span> <span class="nav-text">effect 清除函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#react-hooks-%E7%AB%9E%E6%80%81"><span class="nav-number">5.</span> <span class="nav-text">react hooks 竞态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89-hooks"><span class="nav-number">6.</span> <span class="nav-text">自定义 hooks</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#hooks-%E4%BD%BF%E7%94%A8%E8%A7%84%E5%88%99"><span class="nav-number">7.</span> <span class="nav-text">hooks 使用规则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#React-Hooks-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="nav-number">8.</span> <span class="nav-text">React Hooks 注意事项</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useMemo"><span class="nav-number">9.</span> <span class="nav-text">useMemo</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useCallback"><span class="nav-number">10.</span> <span class="nav-text">useCallback</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useRef-%E4%BF%9D%E5%AD%98%E5%BC%95%E7%94%A8%E5%80%BC"><span class="nav-number">11.</span> <span class="nav-text">useRef(保存引用值)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useReducer%E5%92%8CuseContext-%E5%87%8F%E5%B0%91%E7%BB%84%E4%BB%B6%E5%B1%82%E7%BA%A7"><span class="nav-number">12.</span> <span class="nav-text">useReducer和useContext(减少组件层级)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#React-forwardRef%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="nav-number">13.</span> <span class="nav-text">React.forwardRef的使用方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#react-useImperativeHandle%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">14.</span> <span class="nav-text">react  useImperativeHandle的使用</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">郭泽</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">51</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gz1234.gitee.io/2020/10/25/react%E7%AC%94%E8%AE%B0/react-hooks/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="郭泽">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郭泽">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="react-hooks | 郭泽">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react-hooks
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-10-25 10:08:09" itemprop="dateCreated datePublished" datetime="2020-10-25T10:08:09+08:00">2020-10-25</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-03-22 19:56:23" itemprop="dateModified" datetime="2023-03-22T19:56:23+08:00">2023-03-22</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="认识-hooks"><a href="#认识-hooks" class="headerlink" title="认识 hooks"></a>认识 hooks</h2><ul>
<li><p>Hook 是⼀一个特殊的函数，它可以让你“钩⼊入” React 的特性。例例如， useState 是允许你在 React 函数组件中添加 state 的 Hook</p>
</li>
<li><p>如果你在编写函数组件并意识到需要向其添加⼀一些 state，以前的做法是必须将其它转化为 class。现在你可以在现有的函数组件中使⽤用 Hook</p>
</li>
<li><p>函数组件强制刷新   const [,setCount] = useState({});  不传递一个值</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">HookPage</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 声明⼀一个叫 “count” 的 state 变量量，初始化为0</span></span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(<span class="number">0</span>);</span><br><span class="line">  <span class="comment">// 惰性初始 state值</span></span><br><span class="line">  <span class="keyword">const</span> [count1, setCount1] = useState(<span class="function">() =&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="number">11111</span>); <span class="comment">// 只执行一次</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;h3&gt;HookPage&lt;/h3&gt;</span><br><span class="line">      &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;add&lt;/button&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="使⽤-Effect-Hook"><a href="#使⽤-Effect-Hook" class="headerlink" title="使⽤ Effect Hook"></a>使⽤ Effect Hook</h2><ul>
<li>Effect Hook 可以让你在函数组件中执⾏行行副作⽤用操作。<br>数据获取，设置订阅以及⼿手动更更改 React 组件中的 DOM 都属于副作⽤用。不不管你知不不知道这些操作，或<br>是“副作⽤用”这个名字，应该都在组件中使⽤用过它们。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState, useEffect &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">HookPage</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 声明⼀一个叫 “count” 的 state 变量量，初始化为0</span></span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(<span class="number">0</span>);</span><br><span class="line">  <span class="comment">// 与 componentDidMount 和 componentDidUpdate相似</span></span><br><span class="line">  useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 更更新 title</span></span><br><span class="line">    <span class="built_in">document</span>.title = <span class="string">`You clicked <span class="subst">$&#123;count&#125;</span> times`</span>;</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;h3&gt;HookPage&lt;/h3&gt;</span><br><span class="line">      &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;add&lt;/button&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在函数组件主体内（这⾥里里指在 React 渲染阶段）改变 DOM、添加订阅、设置定时器器、记录⽇日志以及执<br>⾏行行其他包含副作⽤用的操作都是不不被允许的，因为这可能会产⽣生莫名其妙的 bug 并破坏 UI 的⼀一致性。<br>使⽤用 useEffect 完成副作⽤用操作。赋值给 useEffect 的函数会在组件渲染到屏幕之后执⾏行行。你可以<br>把 effect 看作从 React 的纯函数式世界通往命令式世界的逃⽣生通道。</p>
<h2 id="effect-的条件执⾏"><a href="#effect-的条件执⾏" class="headerlink" title="effect 的条件执⾏"></a>effect 的条件执⾏</h2><p>默认情况下，effect 会在每轮组件渲染完成后执行。这样的话，一旦 effect 的依赖发⽣生变化，它就会被<br>重新创建。<br>然⽽而，在某些场景下这么做可能会矫枉过正。⽐如，在上⼀一章节的订阅示例例中，我们不需要在每次组件<br>更新时都创建新的订阅，⽽而是仅需要在 source props 改变时重新创建。<br>要实现这⼀点，可以给 useEffect 传递第⼆个参数，它是 effect 所依赖的值数组。更更新后的示例例如<br>下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState, useEffect &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">HookPage</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 声明⼀一个叫 “count” 的 state 变量量，初始化为0</span></span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(<span class="number">0</span>);</span><br><span class="line">  <span class="keyword">const</span> [date, setDate] = useState(<span class="keyword">new</span> <span class="built_in">Date</span>());</span><br><span class="line">  <span class="comment">// 与 componentDidMount 和 componentDidUpdate相似</span></span><br><span class="line">  useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 更更新 title</span></span><br><span class="line">    <span class="built_in">document</span>.title = <span class="string">`You clicked <span class="subst">$&#123;count&#125;</span> times`</span>;</span><br><span class="line">  &#125;, [count]);</span><br><span class="line">  useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> timer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      setDate(<span class="keyword">new</span> <span class="built_in">Date</span>());</span><br><span class="line">    &#125;, <span class="number">1000</span>);</span><br><span class="line">  &#125;, []);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;h3&gt;HookPage&lt;/h3&gt;</span><br><span class="line">      &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;add&lt;/button&gt;</span><br><span class="line">      &lt;p&gt;&#123;date.toLocaleTimeString()&#125;&lt;/p&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时，只有当 useEffect 第⼆个参数组⾥的数值改变后才会重新创建订阅<br>但依赖项为[],在初次渲染和卸载的时候执行</p>
<h2 id="effect-清除函数"><a href="#effect-清除函数" class="headerlink" title="effect 清除函数"></a>effect 清除函数</h2><p>组件卸载时需要清除 effect 创建的诸如订阅或计时器器 ID 等资源。要实现这⼀一点， useEffect<br>函数需返回⼀个清除函数，以防⽌止内存泄漏漏，清除函数会在组件卸载前执⾏行行。</p>
<p>useEffect 依赖[]，组件销毁是执行 fn，等于 WilUnMount<br>useEffect 无依赖或依赖[a,b]，组件更新时执行fn<br>即，下一次执行 useEffect 之前，就会执行 fn，无论更新或卸载<br>执行实际</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> timer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    setDate(<span class="keyword">new</span> <span class="built_in">Date</span>());</span><br><span class="line">  &#125;, <span class="number">1000</span>);</span><br><span class="line">  <span class="keyword">return</span> <span class="function">() =&gt;</span> <span class="built_in">clearInterval</span>(timer);</span><br><span class="line">&#125;, []);</span><br></pre></td></tr></table></figure>

<h2 id="react-hooks-竞态"><a href="#react-hooks-竞态" class="headerlink" title="react hooks 竞态"></a>react hooks 竞态</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> didSearch = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (text) &#123;</span><br><span class="line">        dispatch</span><br><span class="line">            (&#123;</span><br><span class="line">                type: <span class="string">&#x27;search/fundSearchApp&#x27;</span>,</span><br><span class="line">                payload: &#123; <span class="attr">input</span>: text, <span class="attr">pageSize</span>: <span class="number">20</span>, <span class="attr">isQueryPerformance</span>: <span class="literal">true</span> &#125;</span><br><span class="line">            &#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (!didSearch) &#123;</span><br><span class="line">                    setSearchList(res.searchList)</span><br><span class="line">                    setCurrent(res.current)</span><br><span class="line">                    setTotal(res.total)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        setSearchList([]);</span><br><span class="line">        setCurrent(<span class="number">1</span>);</span><br><span class="line">        setTotal(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        didSearch = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;, [text])</span><br></pre></td></tr></table></figure>

<p>定义一个字段didSearch利用JS的闭包，每次都是不同的变量，在下一次text变化完成，useEffect会再次执行（渲染页面再去调用return方法再去执行useEffect），如果接口没有返回重新渲染了标识会改变使更新逻辑不再执行。</p>
<h2 id="自定义-hooks"><a href="#自定义-hooks" class="headerlink" title="自定义 hooks"></a>自定义 hooks</h2><p>自定义 Hook 是⼀一个函数，其名称以 “use” 开头，函数内部可以调⽤用其他的 Hook。<br><code>&lt;p&gt;&#123;useClock().toLocaleTimeString()&#125;&lt;/p&gt;</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//⾃自定义hook，命名必须以use开头</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">useClock</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [date, setDate] = useState(<span class="keyword">new</span> <span class="built_in">Date</span>());</span><br><span class="line">  useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;date effect&quot;</span>);</span><br><span class="line">    <span class="comment">//只需要在didMount时候执⾏行行就可以了了</span></span><br><span class="line">    <span class="keyword">const</span> timer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      setDate(<span class="keyword">new</span> <span class="built_in">Date</span>());</span><br><span class="line">    &#125;, <span class="number">1000</span>);</span><br><span class="line">    <span class="comment">//清除定时器器，类似willUnmount</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function">() =&gt;</span> <span class="built_in">clearInterval</span>(timer);</span><br><span class="line">  &#125;, []);</span><br><span class="line">  <span class="keyword">return</span> date;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="hooks-使用规则"><a href="#hooks-使用规则" class="headerlink" title="hooks 使用规则"></a>hooks 使用规则</h2><ul>
<li>只能在函数最外层调⽤用 Hook。不要在循环、条件判断或者⼦子函数中调⽤用。</li>
<li>hooks 严重依赖于调用的顺序</li>
<li>只能在 React 的函数组件中调⽤用 Hook。不要在其他 JavaScript 函数中调⽤用。（还有⼀个地⽅方可<br>以调⽤用 Hook —— 就是⾃自定义的 Hook 中。）</li>
</ul>
<h2 id="React-Hooks-注意事项"><a href="#React-Hooks-注意事项" class="headerlink" title="React Hooks 注意事项"></a>React Hooks 注意事项</h2><ul>
<li><p>useState 初始化值，只有第一次有效</p>
</li>
<li><p>useEffect 内部不能修改 state 当依赖为[]时<br>解决方法<br>1 第二参数不传入依赖或者传入修改的那个state；<br>2 可以借助 useRef<br>3 可以借助临时变量，在useEffect 外面定义一个变量做转换</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> [count, setCount] = useState(<span class="number">0</span>)</span><br><span class="line">  <span class="keyword">const</span> countRef = useRef(<span class="number">0</span>)</span><br><span class="line"> useEffect(<span class="function">() =&gt;</span> &#123; </span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&#x27;useEffect...&#x27;</span>, count)</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 定时任务</span></span><br><span class="line">      <span class="keyword">const</span> timer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">          <span class="built_in">console</span>.log(<span class="string">&#x27;setInterval...&#x27;</span>, countRef.current)</span><br><span class="line">          <span class="comment">//  禁止setCount(count + 1)</span></span><br><span class="line">          setCount(++countRef.current)</span><br><span class="line">      &#125;, <span class="number">1000</span>)</span><br><span class="line">      <span class="keyword">return</span> <span class="function">() =&gt;</span> <span class="built_in">clearTimeout</span>(timer)</span><br><span class="line">  &#125;, []) <span class="comment">// 依赖为 []</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>useEffect 可能出现死循环<br>依赖中尽量不要出现引用类型的值</p>
</li>
</ul>
<h2 id="useMemo"><a href="#useMemo" class="headerlink" title="useMemo"></a>useMemo</h2><p>把“创建”函数和依赖项数组作为参数传⼊入 useMemo ，它仅会在某个依赖项改变时才重新计算 memoized 值。这种优化有助于避免在每次渲染时都进⾏行行⾼高开销的计算</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState, useMemo &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">UseMemoPage</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(<span class="number">0</span>);</span><br><span class="line">  <span class="keyword">const</span> expensive = useMemo(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;compute&quot;</span>);</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; count; i++) &#123;</span><br><span class="line">      sum += i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">    <span class="comment">//只有count变化，这⾥里里才重新执⾏行行</span></span><br><span class="line">  &#125;, [count]);</span><br><span class="line">  <span class="keyword">const</span> [value, setValue] = useState(<span class="string">&quot;&quot;</span>);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;h3&gt;UseMemoPage&lt;/h3&gt;</span><br><span class="line">      &lt;p&gt;expensive:&#123;expensive&#125;&lt;/p&gt;</span><br><span class="line">      &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;add&lt;/button&gt;</span><br><span class="line">      &lt;input value=&#123;value&#125; onChange=&#123;<span class="function">(<span class="params">event</span>) =&gt;</span> setValue(event.target.value)&#125; /&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="useCallback"><a href="#useCallback" class="headerlink" title="useCallback"></a>useCallback</h2><p>把内联回调函数及依赖项数组作为参数传⼊入 useCallback ，它将返回该回调函数的 memoized 版本，<br>该回调函数仅在某个依赖项改变时才会更更新。当你把回调函数传递给经过优化的并使⽤用引⽤用相等性去避<br>免⾮非必要渲染（例例如 shouldComponentUpdate ）的⼦子组件时，它将⾮非常有⽤用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState, useCallback, PureComponent &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">UseCallbackPage</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(<span class="number">0</span>);</span><br><span class="line">  <span class="keyword">const</span> addClick = useCallback(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; count; i++) &#123;</span><br><span class="line">      sum += i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">  &#125;, [count]);</span><br><span class="line">  <span class="keyword">const</span> [value, setValue] = useState(<span class="string">&quot;&quot;</span>);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;h3&gt;UseCallbackPage&lt;/h3&gt;</span><br><span class="line">      &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">      &lt;button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;add&lt;/button&gt;</span><br><span class="line">      &lt;input value=&#123;value&#125; onChange=&#123;<span class="function">(<span class="params">event</span>) =&gt;</span> setValue(event.target.value)&#125; /&gt;</span><br><span class="line">      &lt;Child addClick=&#123;addClick&#125; /&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Child</span> <span class="keyword">extends</span> <span class="title">PureComponent</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;child render&quot;</span>);</span><br><span class="line">    <span class="keyword">const</span> &#123; addClick &#125; = <span class="built_in">this</span>.props;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &lt;h3&gt;Child&lt;/h3&gt;</span><br><span class="line">        &lt;button onClick=&#123;<span class="function">() =&gt;</span> <span class="built_in">console</span>.log(addClick())&#125;&gt;add&lt;/button&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>useCallback(fn, deps) 相当于 useMemo(() =&gt; fn, deps) 。</code><br>依赖项数组不不会作为参数传给“创建”函数。虽然从概念上来说它表现为：所有“创建”函数中引⽤用的<br>值都应该出现在依赖项数组中。未来编译器器会更更加智能，届时⾃自动创建数组将成为可能</p>
<h2 id="useRef-保存引用值"><a href="#useRef-保存引用值" class="headerlink" title="useRef(保存引用值)"></a>useRef(保存引用值)</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> myswiper = useRef(<span class="literal">null</span>);  </span><br><span class="line">&lt;Swiper ref=&#123;myswiper&#125;/&gt; </span><br></pre></td></tr></table></figure>

<h2 id="useReducer和useContext-减少组件层级"><a href="#useReducer和useContext-减少组件层级" class="headerlink" title="useReducer和useContext(减少组件层级)"></a>useReducer和useContext(减少组件层级)</h2><p> useReducer 是 useState 的代替方案，用于 state 复杂变化,useReducer 是单个组件状态管理，组件通讯还需要 props</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"><span class="keyword">var</span> GlobalContext= React.createContext()</span><br><span class="line"><span class="comment">// 注意此时的reduecer 返回值是一个对象 &#123;isShow:false,list:[]&#125;</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params">props</span>)</span>&#123;</span><br><span class="line"> </span><br><span class="line">  <span class="keyword">let</span> [state,dispatch]  = useReducer(reducer,&#123;<span class="attr">isShow</span>:<span class="literal">true</span>,<span class="attr">list</span>:[]&#125;)</span><br><span class="line">  <span class="keyword">return</span>  <span class="xml"><span class="tag">&lt;<span class="name">GlobalContext.Provider</span> <span class="attr">value</span>=<span class="string">&#123;&#123;</span></span></span></span><br><span class="line"><span class="xml">    dispatch</span></span><br><span class="line"><span class="xml"> &#125;&#125;&gt;</span></span><br><span class="line">    &lt;div&gt;</span><br><span class="line">     &#123;</span><br><span class="line">        state.isShow?</span><br><span class="line">        &lt;div &gt;我是选项卡&lt;/div&gt;</span><br><span class="line">       :null</span><br><span class="line">     &#125;</span><br><span class="line">     &#123;props.children&#125;</span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;/<span class="name">GlobalContext.Provider</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Detail</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> &#123;dispatch&#125; = useContext(GlobalContext)</span><br><span class="line">  useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">//隐藏</span></span><br><span class="line">    dispatch(&#123;</span><br><span class="line">      type:<span class="string">&quot;Hide&quot;</span>,</span><br><span class="line">      payload:<span class="literal">false</span></span><br><span class="line">   &#125;)</span><br><span class="line">    <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">//显示</span></span><br><span class="line">      dispatch(&#123;</span><br><span class="line">        type:<span class="string">&quot;Show&quot;</span>,</span><br><span class="line">        payload:<span class="literal">true</span></span><br><span class="line">     &#125;)</span><br><span class="line">   &#125;;</span><br><span class="line"> &#125;, [])</span><br><span class="line">  <span class="keyword">return</span> &lt;div&gt;</span><br><span class="line">    detail</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="React-forwardRef的使用方式"><a href="#React-forwardRef的使用方式" class="headerlink" title="React.forwardRef的使用方式"></a>React.forwardRef的使用方式</h2><p>引用传递（Ref forwading）是一种通过组件向子组件自动传递 引用ref 的技术。对于应用者的大多数组件来说没什<br>么作用。但是对于有些重复使用的组件，可能有用。例如某些input组件，需要控制其focus，本来是可以使用ref来<br>控制，但是因为该input已被包裹在组件中，这时就需要使用Ref forward来透过组件获得该input的引用。可以透传<br>多层</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; Component,forwardRef &#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">App_forwardRef</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  mytext=React.createRef()</span><br><span class="line">  <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">      &lt;button type=<span class="string">&quot;button&quot;</span> onClick=&#123;<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.mytext);</span><br><span class="line">        <span class="built_in">this</span>.mytext.current.value=<span class="string">&quot;2222&quot;</span></span><br><span class="line">      &#125;&#125;&gt;获取焦点&lt;/button&gt;</span><br><span class="line">      &lt;Child ref=&#123;<span class="built_in">this</span>.mytext&#125;/&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这里Child是函数式组件</span></span><br><span class="line"><span class="keyword">const</span> Child=forwardRef(<span class="function">(<span class="params">props,ref</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &lt;input defaultValue=<span class="string">&quot;11111&quot;</span> ref=&#123;ref&#125;&gt;&lt;/input&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="react-useImperativeHandle的使用"><a href="#react-useImperativeHandle的使用" class="headerlink" title="react  useImperativeHandle的使用"></a>react  useImperativeHandle的使用</h2><p><code>useImperativeHandle(ref, createHandle, [deps])</code><br>useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值。在大多数情况下，应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 forwardRef 一起使用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">FancyInput</span>(<span class="params">props, ref</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> inputRef = useRef();</span><br><span class="line">  useImperativeHandle(ref, <span class="function">() =&gt;</span> (&#123;</span><br><span class="line">    focus: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      inputRef.current.focus();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;));</span><br><span class="line">  <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">input</span> <span class="attr">ref</span>=<span class="string">&#123;inputRef&#125;</span> <span class="attr">...</span> /&gt;</span></span>;</span><br><span class="line">&#125;</span><br><span class="line">FancyInput = forwardRef(FancyInput);</span><br><span class="line"></span><br><span class="line"><span class="comment">//渲染s时 &lt;FancyInput ref=&#123;inputRef&#125; /&gt; 的父组件可以调用 inputRef.current.focus()。</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react-hooks/" rel="tag"># react-hooks</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2020/10/25/react%E7%AC%94%E8%AE%B0/React-Redux/" rel="prev" title="react-redux">
                  <i class="fa fa-chevron-left"></i> react-redux
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2020/10/26/react%E7%AC%94%E8%AE%B0/MiddleWare%E5%BA%94%E7%94%A8/" rel="next" title="react  redux中间件">
                  react  redux中间件 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">郭泽</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>

  <script class="next-config" data-name="pdf" type="application/json">{"object_url":{"url":"https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.2.8/pdfobject.min.js","integrity":"sha256-tu9j5pBilBQrWSDePOOajCUdz6hWsid/lBNzK4KgEPM="},"url":"/lib/pdf/web/viewer.html"}</script>
  <script src="/js/third-party/tags/pdf.js"></script>

  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":{"light":"default","dark":"dark"},"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.1.3/mermaid.min.js","integrity":"sha256-TIYL00Rhw/8WaoUhYTLX9SKIEFdXxg+yMWSLVUbhiLg="}}</script>
  <script src="/js/third-party/tags/mermaid.js"></script>

  <script src="/js/third-party/fancybox.js"></script>


  





</body>
</html>
